package com.zlgs.cqyf.vote;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;


public class SendMailServlet12 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private  String emailAccount = "";
	private  String emailPassword = "";
	private  String emailSMTPHost = "";
	private  String receviMail = "";
	private  String smtpPort = "";

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.emailAccount = config.getInitParameter("emailAccount");
		this.emailPassword = config.getInitParameter("emailPassword");
		this.emailSMTPHost = config.getInitParameter("emailSMTPHost");
		this.receviMail 	= config.getInitParameter("receviMail");
		this.smtpPort 	= config.getInitParameter("smtpPort");

	}

	public SendMailServlet12() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String msgContent = request.getParameter("msgContent");
		response.getWriter().append("this requst just support post request! " +msgContent);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter printWriter = null;
		JSONObject retObject = new JSONObject();
		try {
			retObject.put("code", 200);
			retObject.put("msg", "success");
			printWriter = response.getWriter();
			
			
			String msgContent = request.getParameter("msgContent");
			if (null == msgContent || "".equals(msgContent)) {
				// 终止程序执行-直接finally
				throw new RuntimeException("发送内容不能为空!");
			}
			
			ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
			//从用户信息表查询出目标用户逐个发送邮件
			String[] mails = receviMail.split(";");
			if(mails.length>0){
				for (String mail : mails) {
					cachedThreadPool.execute(new SendMail(mail,msgContent));
				}
			}
			 
		} catch (Exception e) {
			e.printStackTrace();
			retObject.put("code", -1);
			retObject.put("msg", e.getMessage());
		}finally {
			printWriter.print(retObject.toString());
		} 
	}

	 class SendMail implements Runnable {
		private  String receiveMailAccount;
		private  String msgContent;

		public SendMail(String receiveMailAccount, String msgContent) {
			this.receiveMailAccount = receiveMailAccount;
			this.msgContent = msgContent;
		}

		@Override
		public void run() {
			try {
				Properties props = new Properties(); // 参数配置
				props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议（JavaMail规范要求）
				props.setProperty("mail.smtp.host", emailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
				props.setProperty("mail.smtp.starttls.enable", "true");  
				props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
//				final String smtpPort = "465";
//				final String smtpPort = "25";
				props.setProperty("mail.smtp.port", smtpPort);
				props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
				props.setProperty("mail.smtp.socketFactory.fallback", "false");
				Session session = Session.getDefaultInstance(props);
				session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
				MimeMessage message = createMimeMessage(session, emailAccount, receiveMailAccount);
				// 4. 根据 Session 获取邮件传输对象
				Transport transport = session.getTransport();
				transport.connect(emailAccount, emailPassword);
				// 密送人
				transport.sendMessage(message, message.getAllRecipients());
				// 7. 关闭连接
				transport.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		public   MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail)
				throws Exception {
			// 1. 创建一封邮件
			MimeMessage message = new MimeMessage(session);
			// 2. From: 发件人
			message.setFrom(new InternetAddress(sendMail, emailAccount, "UTF-8"));
			// 3. To: 收件人（可以增加多个收件人、抄送、密送）
			message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));
			// 4. Subject: 邮件主题
			message.setSubject("投投票活动通知！", "UTF-8");
			// 5. Content: 邮件正文（可以使用html标签）
			message.setContent(msgContent, "text/html;charset=UTF-8");
			// 6. 设置发件时间
			message.setSentDate(new Date());
			// 7. 保存设置
			message.saveChanges();
			return message;
		}

	}

}
